package uns.fit.gis.alg;

import java.util.Vector;

import uns.fit.gis.mapobj.Point;

public class RoutingAlgorithm2 {
	public RoutingAlgorithm[][] pairs;
	private int[][] distanceMatrix;
	public Vector points;
	public Tsp tsp;
	
	public RoutingAlgorithm2() {
		points = new Vector();
	}
	
	/*
	 * Add new point
	 */
	public void add(int x, int y) {
		points.addElement(new Point(x, y));
	}
	
	/*
	 * Remove point near (x, y)
	 */
	public void remove(int x, int y) {
		//TODO: remove point
	}
	
	private void init() {
		int n = points.size();
		System.out.println("POINTS = " + points.size());
		distanceMatrix = new int[n][n];
		pairs = new RoutingAlgorithm[n][n];
		for(int i = 0; i < n; i ++)
			for(int j = 0; j < n; j ++) {
				if(i == j) {
					distanceMatrix[i][j] = 0;
				}
				else {
					pairs[i][j] = new RoutingAlgorithm();
					Point point0 = (Point)points.elementAt(i);
					Point point1 = (Point)points.elementAt(j);
					pairs[i][j].setSource(point0.getX(), point0.getY());
					pairs[i][j].setDestination(point1.getX(), point1.getY());
					pairs[i][j].runDijstraAlg();
					/*System.out.println(*/pairs[i][j].routeToString()/*)*/;
					distanceMatrix[i][j] = pairs[i][j].getTotalLength();
				}
			}
	}
	
	public double run() {
		init();
		tsp = new Tsp(distanceMatrix, 0);
		return tsp.repeatetiveNearestNeighbour();
	}
	
	public String getResult() {
		StringBuffer strBuf = new StringBuffer();
		if(tsp != null) {
			for(int i = 0; i < tsp.route.length - 1; i ++) {
				strBuf.append(pairs[tsp.route[i]][tsp.route[i + 1]].routeToString());
				strBuf.append("\n");
			}
		}
		return strBuf.toString();
	}
}
